package chat;

import java.util.Arrays;

import response.MapHeader;
import utils.Conversions;

public class ChatPacket {
	int packetLength;
	int myId;
	int msgLength;
	String msg;
	
	public int getMyId() { return myId; }
	public String getMSg() { return msg; }
	public int getPacketLength() { return packetLength; }
	public void setMsg( String s ) { msg = s; }
	
	public ChatPacket(int id, String m){
		myId = id;
		msg = m;
		msgLength = m.length();
		packetLength = 4 + msgLength;
	}
	
	public ChatPacket(byte[] response){
		byte[] senderInBytes = Arrays.copyOfRange(response, 0, 2);
		byte[] msgInBytes = Arrays.copyOfRange(response, 2, response.length);
		myId = Conversions.bytesToInt(senderInBytes);
		msg = new String( msgInBytes );
		msgLength = msg.length();
		packetLength = -1;
		
		System.out.println( "received chat msg: " + msg);
	}
	
	public byte[] toNetworkByteArray() {
		byte[] blastBodyInBytes = new byte[packetLength ];
		// convert fields to byte arrays
		byte[] rowInBytes = Conversions.intToBytes( myId );
		byte[] colInBytes = Conversions.intToBytes( msgLength );
		
		// concatenate field byte arrays
		System.arraycopy(rowInBytes, 0, blastBodyInBytes, 0, 2);
		System.arraycopy(colInBytes, 0, blastBodyInBytes, 2, 2);
		
		System.arraycopy(msg.getBytes(), 0, blastBodyInBytes, 4, msgLength);
		
		return blastBodyInBytes;
	}
}
